package com.product.magina.wechatserver.service.impl;


import com.google.common.collect.Maps;
import com.magina.common.exception.BusinessException;
import com.product.magina.wechatserver.constant.ProjectConst;
import com.product.magina.wechatserver.dao.DsmtCustomerDao;
import com.product.magina.wechatserver.dao.DsmtPublicWechatDao;
import com.product.magina.wechatserver.entity.DsmtCustomer;
import com.product.magina.wechatserver.entity.DsmtPublicWechat;
import com.product.magina.wechatserver.entity.WeiXinUser;
import com.product.magina.wechatserver.model.PlanCustomerModel;
import com.product.magina.wechatserver.service.DsmtDistributionPlanService;
import com.product.magina.wechatserver.service.WechatService;
import com.product.magina.wechatserver.utils.WeiXinUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("wechatService")
@Slf4j
public class WechatServiceImpl implements WechatService {

	@Autowired
	private DsmtPublicWechatDao dsmtPublicWechatDao;
    @Autowired
    private DsmtCustomerDao dsmtCustomerDao;
    @Autowired
    private DsmtDistributionPlanService dsmtDistributionPlanService;

    @Value(value="${wechat.projectappid}")
    private String projectAppId;

    @Value(value="${wechat.projectappsecret}")
    private String projectAppsecret;

    @Value(value = "${globalbutton.check_customer_phone_stauts}")
    private String checkCustomerPhoneStauts;

    @Override
    public WeiXinUser getUserInfo(String accessToken, String openId) {
        WeiXinUser weixinUserInfo = null;
        // 拼接获取用户信息接口的请求地址
        String requestUrl = ProjectConst.GET_WEIXIN_USER_URL.replace("ACCESS_TOKEN", accessToken).replace(
                "OPENID", openId);
        // 获取用户信息(返回的是Json格式内容)
        JSONObject jsonObject = WeiXinUtils.doGetStr(requestUrl);

        if (null != jsonObject) {
            try {
                //封装获取到的用户信息
                weixinUserInfo = new WeiXinUser();
                // 用户的标识
                weixinUserInfo.setOpenId(jsonObject.getString("openid"));
                // 昵称
                weixinUserInfo.setNickname(jsonObject.getString("nickname"));
                // 用户的性别（1是男性，2是女性，0是未知）
                weixinUserInfo.setSex(jsonObject.getInt("sex"));
                // 用户所在国家
                weixinUserInfo.setCountry(jsonObject.getString("country"));
                // 用户所在省份
                weixinUserInfo.setProvince(jsonObject.getString("province"));
                // 用户所在城市
                weixinUserInfo.setCity(jsonObject.getString("city"));
                // 用户头像
                weixinUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
            } catch (Exception e) {
                if (0 == weixinUserInfo.getSubscribe()) {
                    log.error("用户并没有关注本公众号");
                } else {
                    int errorCode = jsonObject.getInt("errcode");
                    String errorMsg = jsonObject.getString("errmsg");
                    log.error("由于"+errorCode +"错误码；错误信息为："+errorMsg+"；导致获取用户信息失败");
                }
            }
        }
        return weixinUserInfo;
    }

    @Override
    public PlanCustomerModel getPlanListByOpenId(String openId) throws BusinessException {
        PlanCustomerModel model = new PlanCustomerModel();
        if(StringUtils.isEmpty(openId)){
            throw new BusinessException("opendId为空!");
        }
        //判断微信是否和手机在系统内绑定过
        Map map = Maps.newConcurrentMap();
        map.put("openId",openId);
        DsmtPublicWechat publicWechat = dsmtPublicWechatDao.selectByMap(map);
        if(ObjectUtils.isEmpty(publicWechat)){
            model.setFlag(false);
            return model;
        }
        List<DsmtCustomer> customerList = dsmtCustomerDao.selectByPhone(publicWechat.getPhone());
        if (CollectionUtils.isEmpty(customerList) || 0 == customerList.size()){
            if(ProjectConst.CHECK_CUSTOMER_PHONE_STAUTS_OPENING.equals(checkCustomerPhoneStauts)){
                model.setFlag(false);
                return model;
            }else if(ProjectConst.CHECK_CUSTOMER_PHONE_STAUTS_CLOSEING.equals(checkCustomerPhoneStauts)){
                throw new BusinessException("当前用户不在系统内!");
            }
        }
        if ( customerList.size() != 1) {
            throw new BusinessException("手机号码查找客户资料异常!");
        }
        DsmtCustomer customer = customerList.get(0);//暂时只支持一个手机号码对应一个客户
        List planList = dsmtDistributionPlanService.selectPlanByCustomer(customer.getCode());
        model.setDsmtDistributionPlanList(planList);
        model.setDsmtCustomer(customer);
        model.setFlag(true);
        return model;
    }

    /**
     * 进行用户授权，获取到需要的授权字段，比如openId
     * @param code 识别得到用户id必须的一个值
     * 得到网页授权凭证和用户id
     * @return
     */
    @Override
    public Map<String, String> oauth2GetOpenid(String code) {
        //自己的配置appid（公众号进行查阅）
        String appid = projectAppId;
        //自己的配置APPSECRET;（公众号进行查阅）
        String appsecret = projectAppsecret;
        //拼接用户授权接口信息
        String requestUrl = ProjectConst.GET_WEBAUTH_URL.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code);
        //存储获取到的授权字段信息
        Map<String, String> result = new HashMap<String, String>();
        try {
            JSONObject OpenidJSONO = WeiXinUtils.doGetStr(requestUrl);
            //OpenidJSONO可以得到的内容：access_token expires_in  refresh_token openid scope
            String Openid = String.valueOf(OpenidJSONO.get("openid"));
            log.info("openId:"+Openid);
            if(StringUtils.isEmpty(Openid)){
                throw new BusinessException("获取用户微信(openId)失败!");
            }
            String AccessToken = String.valueOf(OpenidJSONO.get("access_token"));
            //用户保存的作用域
            String Scope = String.valueOf(OpenidJSONO.get("scope"));
            String refresh_token = String.valueOf(OpenidJSONO.get("refresh_token"));
            result.put("Openid", Openid);
            result.put("AccessToken", AccessToken);
            result.put("scope", Scope);
            result.put("refresh_token", refresh_token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取到微信用户的唯一的OpendID
     * @param code  这是要获取OpendId的必须的一个参数
     * @return
     */
    @Override
    public Map<String , String> getAuthInfo(String code) {
        //进行授权验证，获取到OpenID字段等信息
        Map<String, String> result = oauth2GetOpenid(code);
        // 从这里可以得到用户openid
        String openId = result.get("Openid");
        return result;
    }

}
